package commons

import (
	"gitee.com/shibingli/fastweb/utils"

	"go.uber.org/zap"
)

type Environment struct {
	noCopy NoCopy

	DevMode bool

	ListenerIP string
	Port       string

	PProfEnable bool

	Concurrency        int
	MaxConnsPerIP      int
	MaxRequestsPerConn int

	StaticDir string

	ContainerMode bool
}

func LoadEnvironment() *Environment {
	e := &Environment{}

	//是否启用开发模式
	if utils.GetENVToBool("DEV_MODE") {
		e.DevMode = true
	}

	//是否启用容器模式
	if utils.GetENVToBool("CONTAINER_MODE") {
		e.ContainerMode = true
	}

	//是否启用PProf
	if utils.GetENVToBool("PPROF_ENABLE") {
		e.PProfEnable = true
	}

	//Web
	e.Port = "8080"
	port := utils.GetENV("SRV_PORT")
	if !utils.IsEmpty(port) {
		e.Port = port
	}

	//获取默认监听IP
	ipv4, err := utils.GetIPs(true)
	if nil != err {
		Logger.Fatal("Utils", zap.String("Get local ip error", err.Error()))
	}

	e.ListenerIP = "0.0.0.0"
	if len(ipv4) > 0 {
		e.ListenerIP = ipv4[0]
	}

	listenerIP := utils.GetENV("SRV_ADDR")
	if !utils.IsEmpty(listenerIP) {
		e.ListenerIP = listenerIP
	}

	//服务器可以服务的最大并发连接数。
	e.Concurrency = 100000
	concurrency := utils.GetENV("SRV_CONCURRENCY")
	if !utils.IsEmpty(concurrency) {
		concurrencyInt, err := utils.StringUtils(concurrency).Int()
		if nil != err {
			Logger.Fatal("Utils", zap.String("Get server concurrency error", err.Error()))
		}
		e.Concurrency = concurrencyInt
	}

	//每个IP允许的最大并发客户端连接数
	e.MaxConnsPerIP = 40000
	maxConnsPerIP := utils.GetENV("SRV_MAX_CONNS_PER_IP")
	if !utils.IsEmpty(maxConnsPerIP) {
		maxConnsPerIPInt, err := utils.StringUtils(maxConnsPerIP).Int()
		if nil != err {
			Logger.Fatal("Utils", zap.String("Get Server MaxConnsPerIP Error", err.Error()))
		}
		e.MaxConnsPerIP = maxConnsPerIPInt
	}

	//每个连接服务的最大请求数
	e.MaxRequestsPerConn = 20000
	maxRequestsPerConn := utils.GetENV("SRV_MAX_REQUESTS_PER_CONN")
	if !utils.IsEmpty(maxRequestsPerConn) {
		maxRequestsPerConnInt, err := utils.StringUtils(maxRequestsPerConn).Int()
		if nil != err {
			Logger.Fatal("Utils", zap.String("Get server MaxRequestsPerConn Error", err.Error()))
		}
		e.MaxRequestsPerConn = maxRequestsPerConnInt
	}

	//静态文件目录
	e.StaticDir = "static"
	staticDir := utils.GetENV("SRV_STATIC_DIR")
	if !utils.IsEmpty(staticDir) {
		e.StaticDir = staticDir
	}

	return e
}
